package com.atguigu.schedule.service.impl;

import com.atguigu.schedule.pojo.*;
import com.atguigu.schedule.service.VideoRecordingService;
import com.atguigu.schedule.service.FFmpegRecordingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 视频录制服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class VideoRecordingServiceImpl implements VideoRecordingService {
    
    private final FFmpegRecordingService ffmpegRecordingService;
    
    @Override
    public RecordingResponse startRecording(StartRecordingRequest request) {
        try {
            // 使用FFmpeg进行真实录制
            RecordingResponse response = ffmpegRecordingService.startRecording(request);
            
            if (response != null) {
                log.info("FFmpeg录制启动成功: {}", response);
            } else {
                log.error("FFmpeg录制启动失败");
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("开始录制失败: {}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public boolean stopRecording(Long recordingId) {
        try {
            // 使用FFmpeg停止录制
            boolean success = ffmpegRecordingService.stopRecording(recordingId);
            if (success) {
                log.info("FFmpeg录制停止成功: {}", recordingId);
            } else {
                log.error("FFmpeg录制停止失败: {}", recordingId);
            }
            return success;
        } catch (Exception e) {
            log.error("停止录制失败: {}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public RecordingResponse getRecordingStatus(Long recordingId) {
        // 这里应该查询实际的录制状态
        RecordingResponse response = new RecordingResponse();
        response.setId(recordingId);
        response.setStatus(RecordingStatus.RECORDING);
        response.setStartTime(LocalDateTime.now().minusHours(1));
        return response;
    }
    
    @Override
    public List<RecordingResponse> getRecordings(RecordingQueryRequest request) {
        // 从文件系统扫描录制文件
        List<RecordingResponse> recordings = scanRecordingFiles(request);
        
        // 分页处理
        int page = request.getPage() != null ? request.getPage() : 0;
        int size = request.getSize() != null ? request.getSize() : 10;
        int start = page * size;
        int end = Math.min(start + size, recordings.size());
        
        if (start >= recordings.size()) {
            return new ArrayList<>();
        }
        
        return recordings.subList(start, end);
    }
    
    @Override
    public List<TimeRange> getRecordingTimeRanges(LocalDate date) {
        List<TimeRange> timeRanges = new ArrayList<>();
        
        // 扫描指定日期的录制文件
        RecordingQueryRequest request = new RecordingQueryRequest();
        request.setStartDate(date.atStartOfDay());
        request.setEndDate(date.atTime(23, 59, 59));
        request.setStatus("COMPLETED");
        
        List<RecordingResponse> recordings = scanRecordingFiles(request);
        
        for (RecordingResponse recording : recordings) {
            TimeRange timeRange = new TimeRange();
            timeRange.setStartTime(recording.getStartTime());
            timeRange.setEndTime(recording.getEndTime());
            timeRange.setDuration(recording.getDuration());
            timeRange.setFilePath(recording.getFilePath());
            timeRange.setFileSize(recording.getFileSize());
            timeRanges.add(timeRange);
        }
        
        return timeRanges;
    }
    
    
    /**
     * 扫描录制文件
     */
    private List<RecordingResponse> scanRecordingFiles(RecordingQueryRequest request) {
        List<RecordingResponse> recordings = new ArrayList<>();
        
        try {
            // SRS录制文件目录
            String recordingsDir = "/usr/local/srs/srs/trunk/objs/nginx/html/recordings/live/livestream";
            File dir = new File(recordingsDir);
            
            log.info("开始扫描录制目录: {}", recordingsDir);
            log.info("目录存在: {}, 是目录: {}", dir.exists(), dir.isDirectory());
            
            if (!dir.exists() || !dir.isDirectory()) {
                log.warn("录制目录不存在: {}", recordingsDir);
                return recordings;
            }
            
            File[] files = dir.listFiles((d, name) -> name.endsWith(".mp4") && !name.endsWith(".tmp"));
            
            log.info("找到 {} 个MP4文件", files != null ? files.length : 0);
            
            if (files == null) {
                return recordings;
            }
            
            for (File file : files) {
                try {
                    RecordingResponse recording = createRecordingFromFile(file);
                    
                    // 应用过滤条件
                    if (matchesFilter(recording, request)) {
                        recordings.add(recording);
                    }
                } catch (Exception e) {
                    log.warn("处理录制文件失败: {}", file.getName(), e);
                }
            }
            
            // 按时间排序
            recordings.sort((a, b) -> {
                if (a.getStartTime() == null || b.getStartTime() == null) {
                    return 0;
                }
                return a.getStartTime().compareTo(b.getStartTime());
            });
            
            log.info("扫描到 {} 个录制文件", recordings.size());
            
        } catch (Exception e) {
            log.error("扫描录制文件失败: {}", e.getMessage(), e);
        }
        
        return recordings;
    }
    
    /**
     * 从文件创建录制响应对象
     */
    private RecordingResponse createRecordingFromFile(File file) {
        RecordingResponse recording = new RecordingResponse();
        
        String fileName = file.getName();
        String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
        
        try {
            LocalDateTime startTime = null;
            Long recordingId = null;
            
            // 尝试解析新格式: yyyyMMdd_HHmmss_timestamp.mp4
            if (baseName.contains("_")) {
                String[] parts = baseName.split("_");
                if (parts.length >= 3) {
                    // 格式: yyyyMMdd_HHmmss_timestamp
                    String dateStr = parts[0]; // yyyyMMdd
                    String timeStr = parts[1]; // HHmmss
                    String timestampStr = parts[2];
                    
                    // 解析日期和时间
                    int year = Integer.parseInt(dateStr.substring(0, 4));
                    int month = Integer.parseInt(dateStr.substring(4, 6));
                    int day = Integer.parseInt(dateStr.substring(6, 8));
                    int hour = Integer.parseInt(timeStr.substring(0, 2));
                    int minute = Integer.parseInt(timeStr.substring(2, 4));
                    int second = Integer.parseInt(timeStr.substring(4, 6));
                    
                    startTime = LocalDateTime.of(year, month, day, hour, minute, second);
                    recordingId = Long.parseLong(timestampStr);
                } else if (parts.length == 2) {
                    // 可能是旧格式或其他格式，尝试解析时间戳
                    try {
                        recordingId = Long.parseLong(parts[parts.length - 1]);
                        startTime = LocalDateTime.ofInstant(
                            java.time.Instant.ofEpochMilli(recordingId),
                            java.time.ZoneId.systemDefault()
                        );
                    } catch (NumberFormatException e) {
                        // 如果解析失败，使用文件修改时间
                        startTime = LocalDateTime.ofInstant(
                            java.time.Instant.ofEpochMilli(file.lastModified()),
                            java.time.ZoneId.systemDefault()
                        );
                        recordingId = file.lastModified();
                    }
                }
            } else {
                // 尝试作为纯时间戳解析（旧格式）
                try {
                    recordingId = Long.parseLong(baseName);
                    startTime = LocalDateTime.ofInstant(
                        java.time.Instant.ofEpochMilli(recordingId),
                        java.time.ZoneId.systemDefault()
                    );
                } catch (NumberFormatException e) {
                    // 使用文件修改时间
                    startTime = LocalDateTime.ofInstant(
                        java.time.Instant.ofEpochMilli(file.lastModified()),
                        java.time.ZoneId.systemDefault()
                    );
                    recordingId = file.lastModified();
                }
            }
            
            // 如果解析失败，使用文件修改时间
            if (startTime == null || recordingId == null) {
                startTime = LocalDateTime.ofInstant(
                    java.time.Instant.ofEpochMilli(file.lastModified()),
                    java.time.ZoneId.systemDefault()
                );
                recordingId = file.lastModified();
            }
            
            // 计算文件时长（简单估算，实际应该从视频元数据获取）
            long fileSize = file.length();
            // 假设码率约1Mbps，估算时长
            int estimatedDuration = (int) (fileSize * 8 / 1024 / 1024); // 秒
            
            recording.setId(recordingId);
            recording.setStreamName("livestream");
            recording.setDescription("监控录制 - " + startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            recording.setStatus(RecordingStatus.COMPLETED);
            recording.setStartTime(startTime);
            recording.setEndTime(startTime.plusSeconds(Math.max(estimatedDuration, 60))); // 至少1分钟
            recording.setDuration(estimatedDuration);
            recording.setFilePath("/recordings/live/livestream/" + fileName);
            recording.setFileSize(fileSize);
            recording.setFormat("mp4");
            
        } catch (Exception e) {
            log.warn("解析文件信息失败: {}", fileName, e);
            // 使用文件修改时间作为备用
            LocalDateTime fileTime = LocalDateTime.ofInstant(
                java.time.Instant.ofEpochMilli(file.lastModified()),
                java.time.ZoneId.systemDefault()
            );
            recording.setId(file.lastModified());
            recording.setStreamName("livestream");
            recording.setDescription("监控录制 - " + fileTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            recording.setStatus(RecordingStatus.COMPLETED);
            recording.setStartTime(fileTime);
            recording.setEndTime(fileTime.plusSeconds(300));
            recording.setDuration(300);
            recording.setFilePath("/recordings/live/livestream/" + fileName);
            recording.setFileSize(file.length());
            recording.setFormat("mp4");
        }
        
        return recording;
    }
    
    /**
     * 检查录制是否匹配过滤条件
     */
    private boolean matchesFilter(RecordingResponse recording, RecordingQueryRequest request) {
        if (recording.getStartTime() == null) {
            return false;
        }
        
        // 时间范围过滤
        if (request.getStartDate() != null && recording.getStartTime().isBefore(request.getStartDate())) {
            return false;
        }
        if (request.getEndDate() != null && recording.getStartTime().isAfter(request.getEndDate())) {
            return false;
        }
        
        // 状态过滤
        if (request.getStatus() != null && !request.getStatus().equals(recording.getStatus().toString())) {
            return false;
        }
        
        // 流名称过滤
        if (request.getStreamName() != null && !request.getStreamName().equals(recording.getStreamName())) {
            return false;
        }
        
        return true;
    }
}
